//
//  UIButton+Extend.m
//  MexicoLoan
//
//  Created by wxp on 2025/2/27.
//

#import "UIButton+Extend.h"
#import <objc/runtime.h>

@implementation UIButton (Extend)

#pragma mark -  防止连点
- (void)setNoRepeatActionWithInterval:(NSTimeInterval)interval action:(void (^)(UIButton *button))action {
    objc_setAssociatedObject(self, &kAssociatedObjectKey_ActionBlock, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
    // 存储 nterval 时间
    objc_setAssociatedObject(self, &kAssociatedObjectKey_Interval, @(interval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonTapped:(UIButton *)sender {
    // 获取并执行 action 块
    void (^action)(UIButton *button) = objc_getAssociatedObject(self, &kAssociatedObjectKey_ActionBlock);
    if (action) {
        action(sender);
    }
    // 禁用按钮，防止再次点击
    self.enabled = NO;
    // 获取存储的interval值
    NSNumber *intervalNumber = objc_getAssociatedObject(self, &kAssociatedObjectKey_Interval);
    NSTimeInterval interval = intervalNumber.doubleValue;
    
    // 延时使按钮可点击
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.enabled = YES;
    });
}


@end
